//
//  HMStatusListViewModel.swift
//  WeiBo
//
//  Created by Apple on 16/9/21.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import SDWebImage

//  封装首页网络请求的ViewModel
class HMStatusListViewModel: NSObject {
    
    //  数据源
    lazy var statusList: [HMStatusViewModel] = [HMStatusViewModel]()

    //  加载数据
    func loadData(isPullup: Bool, callBack: @escaping (Bool)->()) {
        
        var maxId: Int64 = 0
        var sinceId: Int64 = 0
        if isPullup {
            //  上拉加载
            maxId = statusList.last?.status?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            }
        } else {
            sinceId = statusList.first?.status?.id ?? 0
        }
        
        
        let accessToken = HMUserAccountViewModel.sharedUserAccountViewModel.accessToken!
        HMNetworkTools.sharedTools.requestStatuses(accessToken: accessToken, maxId: maxId) { (response, error) in
            
            if error != nil {
                print("网络请求异常: \(error)")
                callBack(false)
                return
            }
            
            //  代码执行到此，网络请求成功
            guard let dic = response as? [String: Any] else {
                print("不是一个正确的字典")
                callBack(false)
                return
            }
            
            guard let dicArray = dic["statuses"] as? [[String: Any]] else {
                print("不是一个正确的字典")
                callBack(false)
                return
            }
            //  使用yymodel解析数组字典
            guard let modelArray = NSArray.yy_modelArray(with: HMStatus.self, json: dicArray) as? [HMStatus] else {
                print("数据解析异常")
                callBack(false)
                return
            }
            var tempArray = [HMStatusViewModel]()
            for model in modelArray {
                let statusViewModel = HMStatusViewModel(status: model)
                tempArray.append(statusViewModel)
                
            }
            
            
            //  代码执行到此 字典没有问题
            //            var tempArray = [HMStatus]()
            //            for value in dicArray {
            //
            ////                let status = HMStatus(dic: value)
            ////                tempArray.append(status)
            //
            //
            //            }
            //  保存数据
//            self.statusList = tempArray
            if isPullup {
                self.statusList.append(contentsOf: tempArray)
            } else {
                self.statusList.insert(contentsOf: tempArray, at: 0)
            }
            
            //  重新刷新数据
//            self.tableView.reloadData()
            
            //  处理单张图片缓存
            self.cacheSingleImage(statusList: tempArray, callBack: callBack)
            
           // callBack(true)
        }
        
        
    }
    
    //  缓存单张配图
    private func cacheSingleImage(statusList: [HMStatusViewModel], callBack: @escaping (Bool)->()) {
        
        //  创建线程组
        let group = DispatchGroup()
        for viewModel in statusList {
            //  原创微博图片是单张
            var imageUrl: String?
            if viewModel.status?.pic_urls?.count == 1 {
                imageUrl = viewModel.status?.pic_urls?.first?.thumbnail_pic
                
            }
            
            if viewModel.status?.retweeted_status?.pic_urls?.count == 1 {
                imageUrl = viewModel.status?.retweeted_status?.pic_urls?.first?.thumbnail_pic
            }
            //  下载单张图片
            if imageUrl != nil {
            
                DispatchQueue.global().async(group: group, qos: DispatchQoS.default, flags: [], execute: { 
                    
                    SDWebImageManager.shared().downloadImage(with: URL(string: imageUrl!)!, options: [], progress: nil, completed: { (image, error, _, _, url) in
                        print("下载完成: \(url)")
                        
                    })
                })
                
            }
        
        }
        
        group.notify(queue: DispatchQueue.main) { 
            callBack(true)
        }
        
    }
    
    
    
}
